<?php
namespace frontend\modules\Api\controllers;

use common\services\TallyService;
use common\services\ToolService;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\base\DynamicModel;
use common\services\TallyStockProductService;

/**
 * Class StockController
 *
 * @package frontend\modules\Api\controllers
 * @desc 库存 产品 管理
 */
class StockProductController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * 产品列表
     * @throws
     */
    public function actionLists()
    {
        $condition = Yii::$app->request->get(); // keywords 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockProductService::getList($tallyId,$condition);
        return self::successResponse($list);
    }

    /**
     * 获取顶多100条初始数据 不带分页 精简返回
     * @throws \yii\base\ExitException
     */
    public function actionAll()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockProductService::getAll($tallyId);
        return self::successResponse($list);
    }

    /**
     * 获取产品详情
     * @throws \yii\base\ExitException
     */
    public function actionInfo()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $productId = Yii::$app->getRequest()->get('product_id');
        if(!$productId){
            return self::failureResponse(500,'产品Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockProductService::getInfo($tallyId,$productId);
        return self::successResponse($list);
    }

    /**
     * 增加产品
     * @throws
     */
    public function actionAdd()
    {
        $form = DynamicModel::validateData([
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'title' => Yii::$app->getRequest()->post('title'),
            'spec' => Yii::$app->getRequest()->post('spec',''),
            'uid'   => $this->_user['id'],
            'unit'  =>Yii::$app->getRequest()->post('unit'),
            'cost_price'  => Yii::$app->getRequest()->post('cost_price',0),
            'sale_price'  => Yii::$app->getRequest()->post('sale_price',0),
            'purchase_price'  => Yii::$app->getRequest()->post('purchase_price',0),
            'memo'  => Yii::$app->getRequest()->post('memo',''),
        ],[
            [['tally_id','title','unit','cost_price'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['title', 'string','min'=> 1,'max'=> 60],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        // 检查用户操作权限
        $this->checkRolePermission($this->_user['id'],$form->tally_id,'read');

        $result = TallyStockProductService::create(ArrayHelper::toArray($form));
        if($result){
            return self::successResponse(['id'=>$result]);
        }else{
            return self::failureResponse(500,'新增失败.'.TallyStockProductService::getError());
        }
    }

    /**
     * 编辑产品
     * @throws
     */
    public function actionEdit()
    {
        $form = DynamicModel::validateData([
            'id'    => Yii::$app->getRequest()->post('id'),
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'title' => Yii::$app->getRequest()->post('title'),
            'spec' => Yii::$app->getRequest()->post('spec',''),
            'unit'  =>Yii::$app->getRequest()->post('unit',''),
            'cost_price'  => Yii::$app->getRequest()->post('cost_price',0),
            'sale_price'  => Yii::$app->getRequest()->post('sale_price',0),
            'purchase_price'  => Yii::$app->getRequest()->post('purchase_price',0),
            'memo'  => Yii::$app->getRequest()->post('memo',''),
        ],[
            [['title','id','tally_id'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['title', 'string','min'=> 1,'max'=> 60],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        // 检查用户操作权限
        $this->checkRolePermission($this->_user['id'],$form->tally_id,'read');

        if(!$form->spec) {
            unset($form->spec);
        }
        if(!$form->unit) {
            unset($form->unit);
        }

        $result = TallyStockProductService::update([
            'id'    => $form->id,
            'tally_id'   => $form->tally_id,
        ],ArrayHelper::toArray($form));
        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'更新失败.'.TallyStockProductService::getError());
        }
    }

    /**
     * 删除产品
     * @throws
     */
    public function actionDel()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'产品Id不能为空');
        }
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本ID不能为空');
        }

        // 检查对账本的操作权限
        $this->checkRolePermission($this->_user['id'],$tallyId,'write');

        $result = TallyStockProductService::delete([
            'id'    => $id,
            'tally_id' => $tallyId,
        ]);

        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'删除失败.'.TallyStockProductService::getError());
        }
    }

    /**
     * 可供选择的产品单位
     * @return array
     */
    public function actionUnitList()
    {
        return ['个','件','台','箱','瓶','平方','桶','把','套','副','只','KG'];
    }

    /**
     * 产品数据导出
     * @throws \yii\base\ExitException
     */
    public function actionExport()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        // 默认取出所有状态 修改返回为data的bug
        $list = TallyStockProductService::getExportAll($condition);
        // 遍历拼装附件数据
        $retData = [] ;
        foreach ($list as $lv) {
            $tmpData = [
                $lv['title'],
                $lv['spec'],
                $lv['unit'],
                $lv['cost_price'],
                $lv['sale_price'],
                $lv['purchase_price'],
                $lv['memo'],
                $lv['created_time'], //录入时间
            ];
            $retData[] = $tmpData;
        }
//        print_r($list);die;
        $filename = '库存产品明细_'.$this->_user['id'].'_'.date('YmdHis').'.csv';
        ToolService::downLoadCsv($filename,[
            '产品名称',
            '产品规格',
            '产品单位',
            '成本价',
            '销售价',
            '采购价',
            '备注',
            '录入时间',
        ],$retData);
        $filepath = Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
        return self::successResponse(['filepath'=>$filepath]);
    }
}
